package calao;

import java.util.HashMap;
import java.util.Vector;

import calao.storage.EqualCondition;
import calao.storage.Record;
import calao.storage.Search;
import calao.storage.Storage;
import calao.util.Cursor;

public class MembershipManager 
extends Service
{
			
	Membership getMembership(long guid)
	{
		Record hit = getStorage().fetch(Membership.TABLE, ws.id, guid);
		return hit!=null? new Membership(ws, hit) : null;
	}
	
	public Membership[] listMembers()
	{
		Search search = new Search(Membership.TABLE);
		search.add(new EqualCondition(Membership.WORKSPACE_ID, ws.id));
		Vector<Membership> result = new Vector<Membership>();
		Cursor<Record> cursor = getStorage().listResults(search);
		try {
			while (cursor.next()) {
				result.add(new Membership(ws, cursor.get()));
			}
		}
		finally {
			cursor.close();
		}
		return result.toArray(new Membership[result.size()]);
	}

	void save(Membership mship)
	{
		if (mship.wsid!=ws.id) throw new IllegalArgumentException();
		storeMembership(ws.id, mship.guid, mship.name, mship.profiles, mship.flags,
				mship.properties, false);
	}
	
	public Membership createMembership(long guid, String name, int[] profiles,
			HashMap<String,String> properties)
	{
		storeMembership(ws.id, guid, name, profiles, 0, properties, true);
		Membership mship = new Membership(ws, guid, name, profiles, 0, properties);
		for (Application app : ws.getApplications()) app.onCreate(mship);
		return mship;
	}
	
	public Membership createMembership(long guid, String name, int[] profiles)
	{
		return createMembership(guid, name, profiles, new HashMap<String,String>());
	}
	
	void storeMembership(int wsid, long guid, String name, int[] profiles, int flags,
			HashMap<String,String> properties, boolean create)
	{
		Record old = getStorage().fetch(Membership.TABLE, ws.id, guid);
		if ((old==null)!=create) throw new IllegalArgumentException();
		Record record = new Record(Membership.TABLE);
		record.set(Membership.WORKSPACE_ID, wsid);
		record.set(Membership.GLOBAL_USER_ID, guid);
		record.set(Membership.NAME, name);
		record.set(Membership.PROFILES, profiles);
		record.set(Membership.FLAGS, flags);
		record.set(Membership.PROPERTIES, properties);
		getStorage().store(record);		
	}
	
	Storage getStorage()
	{
		return ws.server.storage;
	}
	
}
